package com.lyl.xxx.common.config;

import com.lyl.common.config.DefaultGlobalExceptionHandler;
import com.lyl.common.result.BaseCode;
import com.lyl.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author Mr.Luo
 * @date 2022-09-20 10:03
 * @desc 全局异常处理程序
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler extends DefaultGlobalExceptionHandler {

    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(AccessDeniedException.class)
    public Result<Object> onAccessDeniedException(AccessDeniedException e) {
        return Result.build(BaseCode.ACCESS_DENIED).setMsg(e.getMessage());
    }

    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationException.class)
    public Result<Object> onAuthenticationException(AuthenticationException e) {
        return Result.build(BaseCode.UNAUTHORIZED).setMsg(e.getMessage());
    }

    @Override
    public Result<Object> onHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error("post请求体不是json", e);
        return super.onHttpMessageNotReadableException(e);
    }
}
